//
//  WBMainViewController.swift
//  微博
//
//  Created by WangQiang on 2017/8/29.
//  Copyright © 2017年 WangQiang. All rights reserved.
//

import UIKit
/**
 * open > public > interal > fileprivate > private
 * 1，private 访问级别所修饰的属性或者方法只能在当前类里访问。
 
 * 2，fileprivate 访问级别所修饰的属性或者方法在当前的Swift源文件里可以访问。
 
 * 3，internal（默认访问级别，internal修饰符可写可不写）
     internal访问级别所修饰的属性或方法在源代码所在的整个模块都可以访问。
     如果是框架或者库代码，则在整个框架内部都可以访问，框架由外部代码所引用时，则不可以访问。
     如果是App代码，也是在整个App代码，也是在整个App内部可以访问。
 
 * 4，public 可以被任何人访问。但其他module中不可以被override和继承，而在module内可以被override和继承。
 
 * 5，open 可以被任何人使用，包括override和继承
 */
class WBMainViewController: UITabBarController {
    lazy var composeButton = UIButton.init("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
         setupChildControllers()
         setupPlusButton()
        NotificationCenter.default.addObserver(self, selector: #selector(shouldLogin), name: NSNotification.Name.init(WBUserShouldLoginNotification), object: nil)
    }

    /// 撰写微博
    @objc fileprivate func composeStatus() {
        print("撰写微博")
        
    }
    
    @objc fileprivate func shouldLogin(_ nofitiction:NSNotification){
//        DispatchQueue.main.asyncAfter(deadline: <#T##DispatchTime#>, execute: <#T##() -> Void#>)
        let nav  = UINavigationController.init(rootViewController: WBOAuthWebController())
        present(nav, animated: true)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
extension WBMainViewController{
    
    fileprivate func setupPlusButton(){
        tabBar.addSubview(composeButton)
        let w  = tabBar.bounds.width/CGFloat(childViewControllers.count) - 1.0
        //// CGRectInset 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: w*2, dy: 0)
        composeButton.addTarget(self, action: #selector(composeStatus)  , for: .touchUpInside)
    }
   fileprivate func setupChildControllers(){
    
    let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
    let jsonPath = docDir! + "main.json"
     var data  = try? Data.init(contentsOf: URL.init(fileURLWithPath: jsonPath))
    if data == nil {
        let jsonURL = Bundle.main.url(forResource: "main", withExtension: "json")
        data = try? Data.init(contentsOf: jsonURL!, options: .mappedIfSafe)
    }
    guard let json = try? JSONSerialization.jsonObject(with:
        data!, options:.mutableLeaves)  else {
        return
    }
    let array = json as!  [[String : AnyObject]]
    var arrayM = [UIViewController]()
    for dict in array {
        arrayM.append(controller(dict: dict))
    }
    viewControllers = arrayM
    
//    do{
//        let json = try JSONSerialization.jsonObject(with:
//            data, options:.mutableLeaves)
//        
//        let array = json as!  [[String : AnyObject]]
//        var arrayM = [UIViewController]()
//        for dict in array {
//            arrayM.append(controller(dict: dict))
//        }
//        viewControllers = arrayM
//    }catch {
//        print("读取本地数据出错",error)
//    }
    
    
    }
    fileprivate func controller(dict:[String:AnyObject])->UIViewController{
        
        guard let className = dict["clsName"] as? String ,
        let title = dict["title"] as? String,
        let imageName = dict["imageName"] as? String ,
        let cls = WQConvenienceHelp.classFromString(className) as? WBBaseViewController.Type,
        let vistorinfo = dict["visitorInfo"] as? [String:String] else {
            return UIViewController()
        }
        let vc = cls.init()
        vc.title = title
        vc.visitorInfoDictionary = vistorinfo
        vc.tabBarItem.image = UIImage.init(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage.init(named: "tabbar_" +  imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        
        
       let nav = WBMainNavigationController.init(rootViewController: vc)
        return nav;
    }
}
